<?php


namespace App\Admin\Forms\Config;


use App\Models\Config\SystemData;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;

class LinkConfig extends Form
{
    public static function label() :array
    {
        return [
            SystemData::DATA_FRIEND_LINKS =>  "友情链接",
            SystemData::DATA_ABOUT_US=>  "关于我们",
        ];
    }


    public function form()
    {
        $label = static::label();

        $this->table(SystemData::DATA_FRIEND_LINKS,Arr::get($label,SystemData::DATA_FRIEND_LINKS), function (NestedForm $table) {
            $table->text('name')->required();
            $table->url("url")->required();
            $table->number('order')->required();
        });

        $this->table(SystemData::DATA_ABOUT_US,Arr::get($label,SystemData::DATA_ABOUT_US), function (NestedForm $table) {
            $table->text('name')->width(2)->required();
            #$table->select("url")->width(6)->required()->default("sdgagasg")->options(function (){})->ajax("article/match","key")->config("minimumInputLength",3);
            $table->url("url")->required();
            $table->number('order')->required()->width(2);
        });
    }

    /**
     * 处理表单的提交
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $fields = static::label();
        foreach ($fields as $key => $value){
            SystemData::updateOrCreate(["key"=>$key],["name" => $value, "value" => json_encode(Arr::get($input,$key))]);
        }
        return $this->response()->success('设置成功');
    }

    /**
     * 表单默认值
     * @return mixed
     */
    public function default()
    {
        $labels = static::label();
        $all = SystemData::whereIn("key",array_keys($labels))->pluck("value","key");
        $values = [];
        foreach ($labels as $key => $v){
            $value = Arr::get($all,$key);
            $values[$key] = $value ? json_decode($value,JSON_UNESCAPED_UNICODE) : [];
        }
        return $values;
    }


    public function savedScript()
    {
        return <<<'JS'
    if (data.status) {
        setTimeout(function () {
          location.reload()
        }, 1200);
    }
JS;
    }


}
